﻿// -----------------------------------------------------------------------
// <copyright file="GalleryVersionsForm.cs" company="">
// TODO: Update copyright text.
// </copyright>
// -----------------------------------------------------------------------

namespace Sitecore.ChangesTracker.UI
{
  using System;
  using System.Collections.Generic;
  using System.Linq;
  using System.Text;
  using Sitecore.Shell.Applications.ContentManager.Galleries;
  using Sitecore.Data.Items;
  using Sitecore.Diagnostics;
  using Sitecore.Web.UI.XmlControls;
  using System.Globalization;
  using Sitecore.Web.UI.HtmlControls;
  using Sitecore.Web.UI.Sheer;
  using Sitecore.Data;
  using Sitecore.Globalization;
  using Sitecore.Web;
  using Sitecore.Shell.Framework.Commands;
  using Sitecore.Configuration;
  using Sitecore.Collections;

  /// <summary>
  /// TODO: Update summary.
  /// </summary>
  public class GalleryVersionsForm : GalleryForm 
  {
    protected GalleryMenu Options;
    protected Scrollbox Versions;

    protected override void OnLoad(EventArgs e)
    {
      Assert.ArgumentNotNull(e, "e");
      base.OnLoad(e);
      if (!Context.ClientPage.IsEvent)
      {
        string postfix = WebUtil.GetQueryString("view");
        string command = "compare:set" + postfix;
        if (postfix == "_db")
        {
          
          Item currentItem = GetCurrentItem();
          if (currentItem != null)
          {
            Item[] versions = currentItem.Versions.GetVersions();
            for (int i = versions.Length - 1; i >= 0; i--)
            {
              Item item2 = versions[i];
             
              if(postfix=="_db")
              {

                BuildVersionsList(command, currentItem.Version.Number.ToString(),currentItem.Language.Name, currentItem.Statistics.UpdatedBy, currentItem.Statistics.Updated, item2.Version.Number.ToString());
              }
              

            }
          }
        }
        if (postfix == "_cp")
        {
          string versions = WebUtil.GetSessionString("versions");
          if(!string.IsNullOrEmpty(versions))
          {
            StringList verList = new StringList();
            verList.AddRange(versions.Split(new char[]{'|'}));
            string lang = WebUtil.GetSessionString("arc_lang_cp",Sitecore.Context.ContentLanguage.Name);
            string ver= WebUtil.GetSessionString("arc_ver_cp",this.GetLayestVersion(verList));
            for (int i = 0; i < verList.Count - 2; i += 3)
            {
              BuildVersionsList(command,ver, lang, verList[i + 2], DateUtil.ParseDateTime(verList[i + 1],DateTime.MinValue), verList[i]);
            }
          }

          
        }
      }

    }


    private void BuildVersionsList(string command, string CurrentVersion, string currentLanguage, string UpdatedBy, DateTime Updated, string Version)
    {
      XmlControl control = ControlFactory.GetControl("Gallery.Versions.Option") as XmlControl;
      Assert.IsNotNull(control, typeof(XmlControl), "Xml Control \"{0}\" not found", new object[] { "Gallery.Versions.Option" });
      Context.ClientPage.AddControl(this.Versions, control);
      CultureInfo culture = Context.User.Profile.Culture;
      string str = (Updated == DateTime.MinValue) ? Translate.Text("[Not set]") : DateUtil.FormatShortDateTime(Updated, culture);
      string str2 = (UpdatedBy.Length == 0) ? "-" : UpdatedBy;
      string str3 = Version + ".";
      if (Version == CurrentVersion)
      {
        str3 = "<div style=\"border:1px solid #8f99b5;background:#d9eafc;padding:2px 6px 2px 6px\">" + str3 + "</div>";
      }
      else
      {
        str3 = "<div style=\"padding:3px 7px 3px 7px\">" + str3 + "</div>";
      }
      control["Number"] = str3;
      control["Header"] = Translate.Text("Modified <b>{0}</b> by <b>{1}</b>.", new object[] { str, str2 });
      control["Click"] = string.Format(command + "(language={0},version={1})", currentLanguage, Version);
    }

    private string GetLayestVersion(StringList versions)
    {
      int ver = 0;
      for (int i = 0; i < versions.Count - 2; i += 3)
      {
        int num=Convert.ToInt32(versions[i]);
        if ( num > ver)
        {
          ver = num;
        }
      }
      return ver.ToString();
    }

    public override void HandleMessage(Message message)
    {
      Assert.ArgumentNotNull(message, "message");
      if (message.Name != "event:click")
      {
        switch (message.Name)
        {
          case "compare:set_db":
            WebUtil.SetSessionValue("arc_ver_db", message.Arguments["version"]);            
            break;
          case "compare:set_cp":
            WebUtil.SetSessionValue("arc_ver_cp", message.Arguments["version"]); 
            break;
          default:
            base.Invoke(message, true);
            break;
        }       
       // SheerResponse.Eval("scForm.getParentForm().Refresh()");
        SheerResponse.Eval("scForm.getParentForm().invoke(\"archive:refresh\")");
          SheerResponse.Eval("scForm.getParentForm().Content.closeGallery(scForm.browser.getFrameElement().id)");
      }
    }
    private static Item GetCurrentItem()
    {
      //string queryString = WebUtil.GetQueryString("db");
      string str2 = WebUtil.GetSessionString("itm_id");
      string lang = WebUtil.GetSessionString("arc_lang_db");
      Language language =string.IsNullOrEmpty(lang)?Context.ContentLanguage:Language.Parse(lang);
      Sitecore.Data.Version version = Sitecore.Data.Version.Parse(WebUtil.GetSessionString("arc_ver_db")??"0");     
      return Context.ContentDatabase.Items[str2, language, version];
    }



    



  }
}
